package com.wpre.springblog;

import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created with IntelliJ IDEA.
 * Description:响应
 * User: LianBao
 * Date: 2024-10-19
 * Time: 15:03
 */
@RequestMapping("/Response")
//@RestController
@Controller
public class ResponseController {


    /**
     * Controller和RestController的区别:
     * 1. @RestController是根据@Controller来实现的
     * 2. @RestController = @Controller + @ResponseBody ,ResponseBody表示返回数据
     * 3. 如果想返回数据,使用ResponseBody;如果想返回页面,使用Controller
     */

    /**
     * ResponseBody即是类注解,又是方法注解,加在类上表示该类的所有方法都返回数据,加在方法上表示该方法返回数据,其他方法不受影响
     */


    //返回html页面
    @RequestMapping("/r1")
    public String r1() {
        return "/Test.html";
    }

    //返回数据
    @RequestMapping("/r2")
    @ResponseBody
    public String r2() {
        return "Test.html";
    }

    //返回html代码片段
    @RequestMapping("/r3")
    @ResponseBody
    public String r3() {
        return "<h1>你好</h1>";//浏览器会解析成html代码
    }


    //返回json数据
    @ResponseBody
    @RequestMapping("/r4")
    public User r4() {
        User user = new User();

        user.setAge(18);
        user.setName("张三");
        user.setGender("男");

        return user;//虽然这里返回的是user对象,但是实际上返回的就是json
    }

    //设置状态码,使用HttpServletResponse
    @ResponseBody
    @RequestMapping("/r5")
    public String r5(HttpServletResponse response) {
        response.setStatus(500);//设置状态码
        return "状态码设置成功";
    }

    //设置响应的Header,类型
    @RequestMapping(value = "/r6", produces = "application/json")
    @ResponseBody
    public String r6() {

        return "{\"user\":wpre}";
    }

    //设置响应的Header,自定义key,value
    @RequestMapping(value = "/r7")
    @ResponseBody
    public String r7(HttpServletResponse response) {
        response.setHeader("Key1", "value1");
        return "设置成功";
    }


}
